---
title: "Lab 3 Code"
author: "Fabio Setti"
date: "Spring-2026"
output: html_document
---

## Today's Packages and Data 🤗

```{r}
install.packages("GGally")
install.packages("devtools")
install.packages("flextable")
# requires devtools
devtools::install_github("quinix45/FabioFun")
```

```{r}
library(tidyverse)
library(GGally)
library(FabioFun)
theme_set(theme_classic(base_size = 16, accent = "#3492eb", base_family = 'serif'))
```

```{r}
dat <- rio::import("https://fabio-setti.netlify.app/data/World_happiness_2024.csv")
```



## Predicting Country Happiness


```{r}
reg_free <- lm(Happiness_score ~ Freedom, dat)
summary(reg_free)
```

```{r}
reg_corr <- lm(Happiness_score ~ Corruption, dat)
summary(reg_corr)
```


## Well, That's just the correlation 🤷


```{r}
GGally::ggpairs(dat[,c(3, 7,9)])
```


## Multiple Independent Variables

```{r}
reg_multi <- lm(Happiness_score ~ Freedom + Corruption, dat)
summary(reg_multi)
```

## Individual regression plots

```{r}
ggplot(dat,  
 aes(x = Freedom, y = Happiness_score)) +
 geom_point() + 
    geom_smooth(method = "lm",  
                se = FALSE)
```


```{r}
ggplot(dat,  
 aes(x = Corruption, y = Happiness_score)) +
 geom_point() + 
    geom_smooth(method = "lm",  
                se = FALSE)
```

## Adding Multiple regression Lines


```{r}

ggplot(dat,  
 aes(x = Freedom, y = Happiness_score)) +
 geom_point() + 
    geom_smooth(method = "lm",  
                se = FALSE) +
    geom_abline(intercept = coef(reg_multi)[1], 
                slope = coef(reg_multi)[2])
```


```{r}
ggplot(dat,  
 aes(x = Corruption, y = Happiness_score)) +
 geom_point() + 
    geom_smooth(method = "lm",  
                se = FALSE)+
    geom_abline(intercept = coef(reg_multi)[1], 
                slope = coef(reg_multi)[3])
```

## A better Perspective


```{r}
# run "devtools::install_github("quinix45/FabioFun")" if you haven't installed the package yet
library(FabioFun)

nice_3D_plot(y = dat$Happiness_score,
             x1 = dat$Freedom,
             x2 = dat$Corruption,
             dot_labels = dat$Country_name,
             axis_names = c("Happiness", 
                            "Freedom", 
                            "Corruption"))

```


## The Regression *Plane*

```{r}

nice_3D_plot(y = dat$Happiness_score,
             x1 = dat$Freedom,
             x2 = dat$Corruption,
             dot_labels = dat$Country_name,
             axis_names = c("Happiness", 
                            "Freedom", 
                            "Corruption"),
             reg_plane = TRUE)
```

## APA Style Table for Regression Results


```{r}

reg_tab <- FabioFun::regression_flextable(reg_multi, 
                                var_names = c("Freedom", "Corruption"), 
                                intercept = TRUE)
reg_tab
```


```{r}
# save to Word document (will be saved to current working directory)
flextable::save_as_docx(reg_tab, path = "table.docx")
```